import { 
  passwordLogin, 
  codeLogin, 
  register, 
  sendVerifyCode,
  checkUsername,
  checkPhone,
  handleLoginSuccess,
  showApiError,
  showSuccess,
  isLoggedIn
} from './cloud-api';

Page({
  data: {
    phoneNumber: '',
    isPhoneNumber: false,
    isCheck: false,
    isSubmit: false,
    isPasswordLogin: false,
    redirectUrl: '', // 添加redirect参数
    
    // 密码登录数据
    passwordInfo: {
      account: '',
      password: '',
    },
    
    // 验证码相关
    verifyCode: '',
    inviteCode: '',  // 邀请码（可选，新用户必填）
    sendCodeCount: 60,
    isSendingCode: false,
    codeExpireTime: null, // 验证码过期时间
    codeExpireTimer: null, // 过期倒计时定时器
    codeExpireMinutes: 0, // 剩余有效分钟数
    isCodeExpired: false, // 验证码是否已过期
    
    radioValue: '',
  },

  /**
   * 页面加载时处理redirect参数
   */
  onLoad(options) {
    // 获取redirect参数
    const redirectUrl = options.redirect ? decodeURIComponent(options.redirect) : '';
    this.setData({ redirectUrl });
    
    console.log('登录页面加载，redirect参数:', redirectUrl);
    
    // 如果已经登录，直接跳转
    if (isLoggedIn()) {
      console.log('用户已登录，直接跳转');
      this.handleSuccessRedirect();
    }
  },

  /**
   * 处理登录成功后的跳转
   */
  handleSuccessRedirect() {
    const redirectUrl = this.data.redirectUrl;
    
    // 输出登录成功的用户信息
    setTimeout(() => {
      // 延迟一下确保用户信息已保存
      const userInfo = wx.getStorageSync('user_info');
      if (userInfo && userInfo.id) {
        console.log('\n🎉 === 登录成功 ===');
        console.log('👤 用户ID:', userInfo.id);
        console.log('📝 用户名:', userInfo.name || userInfo.username);
        console.log('🏷️ 用户角色:', userInfo.role);
        console.log('📱 手机号:', userInfo.phone);
        console.log('====================\n');
      }
    }, 100);
    
    handleLoginSuccess(redirectUrl);
  },

  /* 自定义功能函数 */
  changeSubmit() {
    let isSubmit = false;
    
    if (this.data.isPasswordLogin) {
      // 密码登录验证
      const { account, password } = this.data.passwordInfo;
      isSubmit = account && password && this.data.isCheck;
    } else {
      // 验证码登录验证（邀请码可选，后端会验证）
      isSubmit = this.data.isPhoneNumber && this.data.verifyCode && this.data.isCheck && !this.data.isCodeExpired;
    }
    
    this.setData({ isSubmit });
  },

  // 手机号变更
  onPhoneInput(e) {
    const isPhoneNumber = /^[1][3,4,5,7,8,9][0-9]{9}$/.test(e.detail.value);
    this.setData({
      isPhoneNumber,
      phoneNumber: e.detail.value,
    });
    this.changeSubmit();
  },

  // 用户协议选择变更
  onCheckChange(e) {
    const { value } = e.detail;
    this.setData({
      radioValue: value,
      isCheck: value === 'agree',
    });
    this.changeSubmit();
  },

  onAccountChange(e) {
    this.setData({ passwordInfo: { ...this.data.passwordInfo, account: e.detail.value } });
    this.changeSubmit();
  },

  onPasswordChange(e) {
    this.setData({ passwordInfo: { ...this.data.passwordInfo, password: e.detail.value } });
    this.changeSubmit();
  },

  // 切换登录方式
  changeLogin() {
    this.setData({ 
      isPasswordLogin: !this.data.isPasswordLogin, 
      isSubmit: false
    });
    this.changeSubmit();
  },

  // 验证码输入
  onVerifyCodeInput(e) {
    console.log('🔢 验证码输入:', e.detail.value);
    this.setData({ verifyCode: e.detail.value });
    console.log('🔢 当前验证码:', this.data.verifyCode);
    this.changeSubmit();
  },

  // 邀请码输入
  onInviteCodeInput(e) {
    this.setData({ inviteCode: e.detail.value });
  },

  // 发送验证码
  async sendCode() {
    console.log('🚀 开始发送验证码');
    
    if (this.data.isSendingCode) return;

    const phone = this.data.phoneNumber;
    const type = 'login';  // 统一使用login类型

    console.log('🚀 获取到的手机号:', phone);
    console.log('🚀 操作类型:', type);

    if (!phone) {
      console.log('❌ 手机号为空！');
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }

    const phoneReg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (!phoneReg.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    this.setData({ isSendingCode: true });

    try {
      const result = await sendVerifyCode({ phone, type });
      
      if (result.success) {
        showSuccess('验证码发送成功');
        this.startCountdown();
        this.startCodeExpireCountdown(); // 开始验证码过期倒计时
      } else {
        showApiError(result);
      }
    } catch (error) {
      console.error('发送验证码失败:', error);
      wx.showToast({
        title: '发送失败，请重试',
        icon: 'none'
      });
    }

    this.setData({ isSendingCode: false });
  },

  // 开始倒计时
  startCountdown() {
    this.setData({ sendCodeCount: 60 });
    const timer = setInterval(() => {
      const count = this.data.sendCodeCount - 1;
      if (count <= 0) {
        clearInterval(timer);
        this.setData({ sendCodeCount: 60 });
      } else {
        this.setData({ sendCodeCount: count });
      }
    }, 1000);
  },

  // 开始验证码过期倒计时
  startCodeExpireCountdown() {
    // 设置过期时间为10分钟后
    const expireTime = new Date(Date.now() + 10 * 60 * 1000);
    this.setData({ 
      codeExpireTime: expireTime,
      isCodeExpired: false,
      codeExpireMinutes: 10
    });

    // 清除之前的定时器
    if (this.data.codeExpireTimer) {
      clearInterval(this.data.codeExpireTimer);
    }

    // 每30秒更新一次剩余时间
    const expireTimer = setInterval(() => {
      const now = new Date();
      const remainingMs = expireTime.getTime() - now.getTime();
      
      if (remainingMs <= 0) {
        // 验证码已过期
        clearInterval(expireTimer);
        this.setData({ 
          isCodeExpired: true,
          codeExpireMinutes: 0,
          codeExpireTimer: null
        });
        this.changeSubmit(); // 重新检查提交状态
        
        wx.showToast({
          title: '验证码已过期，请重新获取',
          icon: 'none',
          duration: 2000
        });
      } else {
        // 更新剩余分钟数
        const remainingMinutes = Math.ceil(remainingMs / (1000 * 60));
        this.setData({ codeExpireMinutes: remainingMinutes });
      }
    }, 30000); // 每30秒检查一次

    this.setData({ codeExpireTimer: expireTimer });
  },

  // 清除验证码过期倒计时
  clearCodeExpireCountdown() {
    if (this.data.codeExpireTimer) {
      clearInterval(this.data.codeExpireTimer);
      this.setData({ 
        codeExpireTimer: null,
        codeExpireTime: null,
        isCodeExpired: false,
        codeExpireMinutes: 0
      });
    }
  },

  // 主要登录方法
  async login() {
    if (!this.data.isSubmit) return;

    wx.showLoading({ title: '处理中...' });

    try {
      if (this.data.isPasswordLogin) {
        await this.handlePasswordLogin();
      } else {
        await this.handleCodeLogin();
      }
    } catch (error) {
      console.error('操作失败:', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    }
    wx.hideLoading();
  },

  // 密码登录
  async handlePasswordLogin() {
    const result = await passwordLogin(this.data.passwordInfo);
    
    if (result.success) {
      showSuccess('登录成功');
      this.handleSuccessRedirect();
    } else {
      showApiError(result);
    }
  },

  // 验证码登录（支持自动注册，包括微信用户注册）
  async handleCodeLogin() {
    console.log('🔐 开始验证码登录/注册');
    console.log('🔐 手机号:', this.data.phoneNumber);
    console.log('🔐 验证码:', this.data.verifyCode);
    console.log('🔐 邀请码:', this.data.inviteCode);
    console.log('🔐 微信用户信息:', this.wechatUserInfo);
    
    // 检查验证码是否过期
    if (this.data.isCodeExpired) {
      wx.showToast({
        title: '验证码已过期，请重新获取',
        icon: 'none'
      });
      return;
    }

    // 如果是微信用户注册，使用wechatRegister接口
    if (this.wechatUserInfo) {
      // 新用户必须填写邀请码
      if (!this.data.inviteCode) {
        wx.showToast({
          title: '新用户注册需要邀请码',
          icon: 'none'
        });
        return;
      }

      wx.showLoading({ title: '注册中...' });
      
      try {
        const result = await wx.cloud.callFunction({
          name: 'login',
          data: {
            action: 'wechatRegister',
            data: {
              wechatInfo: this.wechatUserInfo,
              phone: this.data.phoneNumber,
              verifyCode: this.data.verifyCode,
              inviteCode: this.data.inviteCode
            }
          }
        });

        wx.hideLoading();

        if (result.result.success) {
          // 从 data 中提取数据
          const responseData = result.result.data || result.result;
          
          wx.setStorageSync('access_token', responseData.token);
          wx.setStorageSync('user_info', responseData.userInfo);
          
          showSuccess(`注册成功！获得${responseData.userInfo.points}积分`);
          this.clearCodeExpireCountdown();
          this.wechatUserInfo = null; // 清除微信信息
          this.handleSuccessRedirect();
        } else {
          showApiError(result.result);
        }
      } catch (error) {
        wx.hideLoading();
        console.error('微信注册失败:', error);
        wx.showToast({
          title: '注册失败，请重试',
          icon: 'none'
        });
      }
      return;
    }

    // 普通快速登录/注册
    const result = await codeLogin({
      phone: this.data.phoneNumber,
      verifyCode: this.data.verifyCode,
      inviteCode: this.data.inviteCode  // 传递邀请码（可选）
    });
    
    if (result.success) {
      // 显示成功信息
      const message = result.isNewUser 
        ? `注册成功！获得${result.userInfo.points}积分` 
        : '登录成功';
      showSuccess(message);
      
      this.clearCodeExpireCountdown(); // 清除过期倒计时
      this.handleSuccessRedirect();
    } else {
      showApiError(result);
      // 如果是验证码错误或过期，提示重新获取
      if (result.code === 1005 || result.code === 1006) {
        this.setData({ isCodeExpired: true });
      }
    }
  },


  // 页面卸载时清除定时器
  onUnload() {
    this.clearCodeExpireCountdown();
  },

  // 微信授权登录（老用户直接登录，新用户需要手机号+邀请码）
  async wechatLogin() {
    console.log('🔐 开始微信授权登录');

    try {
      // 获取微信用户信息
      const userProfile = await wx.getUserProfile({
        desc: '用于完善会员资料'
      });

      console.log('微信用户信息:', userProfile.userInfo);

      wx.showLoading({ title: '登录中...' });

      // 调用云函数进行微信登录
      const result = await wx.cloud.callFunction({
        name: 'login',
        data: {
          action: 'wechatLogin',
          data: {
            wechatInfo: userProfile.userInfo
          }
        }
      });

      wx.hideLoading();

      console.log('微信登录结果:', result);

      if (result.result.success && !result.result.data.needRegister) {
        // 老用户，直接登录成功
        wx.setStorageSync('access_token', result.result.data.token);
        wx.setStorageSync('user_info', result.result.data.userInfo);
        
        showSuccess('登录成功');
        this.handleSuccessRedirect();
      } else if (result.result.data.needRegister) {
        // 新用户，需要填写手机号、验证码和邀请码
        this.wechatUserInfo = userProfile.userInfo;
        
        wx.showModal({
          title: '欢迎新用户',
          content: '请填写手机号、验证码和邀请码完成注册',
          showCancel: false,
          confirmText: '知道了'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('微信授权登录失败:', error);
      
      if (error.errMsg && error.errMsg.indexOf('getUserProfile:fail auth deny') !== -1) {
        wx.showToast({
          title: '已取消授权',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        });
      }
    }
  },

});
